package top.lyf1210.yuwenpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.lyf1210.yuwenpicturebackend.annotation.AuthCheck;
import top.lyf1210.yuwenpicturebackend.annotation.SaSpaceCheckPermission;
import top.lyf1210.yuwenpicturebackend.common.BaseResponse;
import top.lyf1210.yuwenpicturebackend.common.ResultUtils;
import top.lyf1210.yuwenpicturebackend.constant.UserAuthConstant;
import top.lyf1210.yuwenpicturebackend.enums.PictureReviewStatusEnum;
import top.lyf1210.yuwenpicturebackend.enums.SpaceLevelEnum;
import top.lyf1210.yuwenpicturebackend.exception.BusinessException;
import top.lyf1210.yuwenpicturebackend.exception.ErrorCode;
import top.lyf1210.yuwenpicturebackend.exception.ThrowUtils;
import top.lyf1210.yuwenpicturebackend.imagesearch.ImageSearchApiFacade;
import top.lyf1210.yuwenpicturebackend.imagesearch.model.ImageSearchResult;
import top.lyf1210.yuwenpicturebackend.manager.auth.constant.SpaceUserPermissionConstant;
import top.lyf1210.yuwenpicturebackend.model.Picture;
import top.lyf1210.yuwenpicturebackend.model.PictureTagCategory;
import top.lyf1210.yuwenpicturebackend.model.Space;
import top.lyf1210.yuwenpicturebackend.model.User;
import top.lyf1210.yuwenpicturebackend.model.dto.picture.*;
import top.lyf1210.yuwenpicturebackend.model.vo.picture.PictureVO;
import top.lyf1210.yuwenpicturebackend.model.vo.space.SpaceLevel;
import top.lyf1210.yuwenpicturebackend.service.PictureService;
import top.lyf1210.yuwenpicturebackend.service.SpaceService;
import top.lyf1210.yuwenpicturebackend.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassNamePictureController
 * @Description 图片上传的控制层
 * @Author钰玟
 * @Date2025/4/17 下午8:10
 * @Version 1.0
 **/
@RestController
//@Api(tags="图片相关接口")
@RequestMapping("/picture")
public class PictureController {
    private static final Logger log = LoggerFactory.getLogger(PictureController.class);
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();



    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SpaceService spaceService;

    @PostMapping("/upload")
    @ApiOperation("图片上传")
//    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile file,
                                                 PictureUploadDTO pictureUploadDTO,
                                                 HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(file,pictureUploadDTO,loginUser);
        return ResultUtils.success(pictureVO);

    }

    @PostMapping("/delete/{id}")
    @ApiOperation("删除图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@PathVariable("id") long id,HttpServletRequest request) {
        //判断删除id的是否合法
        ThrowUtils.throwIf(id<0, ErrorCode.PARAMS_ERROR);
        //获取操作的用户
        User loginUser = userService.getLoginUser(request);
        //service
        Boolean result = pictureService.deletePicture(id,loginUser);

        return ResultUtils.success(result);

    }

    @PostMapping("/update")
    @ApiOperation("更新图片")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateDTO pictureUpdateDTO,HttpServletRequest request){
        //判断dto
        ThrowUtils.throwIf(pictureUpdateDTO==null,ErrorCode.PARAMS_ERROR);
        //dto转换为entity
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureUpdateDTO,picture);
        //注意的是，tags将list转化为String
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateDTO.getTags()));
        //数据校验
        pictureService.validPicture(picture);
        //判断是否存在
        long id = picture.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //审核参数
        pictureService.fillReviewParams(picture,userService.getLoginUser(request));
        //操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }


    @GetMapping("/get")
    @ApiOperation("根据id获取图片(管理员)")
    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPicture( long id,HttpServletRequest request){
        ThrowUtils.throwIf(id<0, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture==null,ErrorCode.NOT_FOUND_ERROR);
        //获取封装类
        return ResultUtils.success(picture);
    }

    @GetMapping("/get/vo")
    @ApiOperation("根据id获取图片(用户端)")
//    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<PictureVO> getPictureVO( long id,HttpServletRequest request){
        ThrowUtils.throwIf(id<0, ErrorCode.PARAMS_ERROR);

        //只能获取已审核的 图片
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id).eq("reviewStatus", PictureReviewStatusEnum.PASS.getValue());


        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            User loginUser = userService.getLoginUser(request);
            //鉴权，改为注解鉴权
//            pictureService.checkPictureAuth(loginUser, picture);
        }
//
//        Picture picture = pictureService.getOne(queryWrapper);
        ThrowUtils.throwIf(picture==null,ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(pictureService.getPictureVO(picture,request));
    }

    @PostMapping("/list/page")
    @ApiOperation("分页获取图片列表管理端")
    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryDTO pictureQueryDTO){
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //TODO 管理端也不能获取私有空间的图片
        //查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current,pageSize)
        , pictureService.getQueryWrapper(pictureQueryDTO));
        return ResultUtils.success(picturePage);
    }


    @PostMapping("list/page/vo")
    @ApiOperation("分页获取图片列表用户端")
    public BaseResponse<Page<PictureVO>> listPictureVO(@RequestBody PictureQueryDTO pictureQueryDTO,HttpServletRequest request) {
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize>20,ErrorCode.PARAMS_ERROR);

        // 空间权限校验
        Long spaceId = pictureQueryDTO.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryDTO.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }
        //查询数据库
        Page<Picture> page = pictureService.page(new Page<>(current,pageSize), pictureService.getQueryWrapper(pictureQueryDTO));

        return ResultUtils.success(pictureService.getPictureVOPage(page,request));
    }

    @PostMapping("/edit")
    @ApiOperation("编辑图片信息")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    /*TODO 目前更新上传图片的逻辑还是存在一些问题的。比如更新图片时，并没有删除原有图片、也没有减少原有图片占用的空间和额度，可以通过事务中补充逻辑或者通过定时任务扫描删除。*/
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditDTO pictureEditDTO, HttpServletRequest request){
        //判断编辑的图片dto
        ThrowUtils.throwIf(pictureEditDTO==null,ErrorCode.PARAMS_ERROR);
        //判断是否具有权限修改该图片
        User loginUser= userService.getLoginUser(request);
        Boolean result = pictureService.editPicture(pictureEditDTO, loginUser);
        return ResultUtils.success(result);
    }
    @GetMapping("/tag_category")
    @ApiOperation("获取标签分类")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }



    @PostMapping("/review")
    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewDTO pictureReviewDTO, HttpServletRequest request) {
        //判断dto
        ThrowUtils.throwIf(pictureReviewDTO==null,ErrorCode.PARAMS_ERROR);
        User user = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewDTO,user);
        return ResultUtils.success(true);
    }


    @PostMapping("upload/url")
    @ApiOperation("根据url上传图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadDTO pictureUploadDTO,HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(pictureUploadDTO.getUrl(),pictureUploadDTO,loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("upload/batch")
    @ApiOperation("批量上传图片")
    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchDTO pictureUploadByBatchDTO,HttpServletRequest request){
        ThrowUtils.throwIf(pictureUploadByBatchDTO==null,ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int result = pictureService.pictureUploadByBatch(pictureUploadByBatchDTO,loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 分页获取图片列表
     * @param pictureQueryDTO
     * @param request
     * @return
     */
    @PostMapping("list/page/vo/cache")
    @ApiOperation("分页获取图片列表redis缓存版")
    public BaseResponse<Page<PictureVO>> listPictureVOWithCache(@RequestBody PictureQueryDTO pictureQueryDTO,HttpServletRequest request) {
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize>20,ErrorCode.PARAMS_ERROR);
        //只能显示已通过审核的图片
        pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        //1.从redis查询数据
        //1.1 redis 的key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryDTO);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = String.format("yuwenpicture:listPictureVOByPage:%s",hashKey);
        //1.2 从redis获取数据
        String cacheValue = stringRedisTemplate.opsForValue().get(redisKey);
        //2.判断缓存是否命中
        if(cacheValue !=null){
            Page<PictureVO> cachePage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        //3.未命中，查询数据库
        Page<Picture> page = pictureService.page(new Page<>(current,pageSize), pictureService.getQueryWrapper(pictureQueryDTO));
        //3.1 封装响应结果 为VO对象
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(page,request);
        //4. 缓存至redis
        String toCache = JSONUtil.toJsonStr(pictureVOPage);
        //4.1 5-10分钟，防止缓存雪崩
        int cacheExpireTime = 300 + RandomUtil.randomInt(0,300);
        stringRedisTemplate.opsForValue().set(redisKey,toCache,cacheExpireTime, TimeUnit.SECONDS);
        //5. 返回数据
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 分页获取图片列表
     * @param pictureQueryDTO
     * @param request
     * @return
     */
    @PostMapping("list/page/vo/caffeine")
    @ApiOperation("分页获取图片列表caffeine缓存版")
    public BaseResponse<Page<PictureVO>> listPictureVOWithCaffeine(@RequestBody PictureQueryDTO pictureQueryDTO,HttpServletRequest request) {
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize>20,ErrorCode.PARAMS_ERROR);
        //只能显示已通过审核的图片
        pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        //1.从caffeine查询数据
        //1.1 caffeine 的key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryDTO);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String caffeineKey = String.format("yuwenpicture:listPictureVOByPage:%s",hashKey);
        //1.2 从caffeine获取数据
        String cacheValue = LOCAL_CACHE.getIfPresent(caffeineKey);
        //2.判断缓存是否命中
        if(cacheValue !=null){
            Page<PictureVO> cachePage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        //3.未命中，查询数据库
        Page<Picture> page = pictureService.page(new Page<>(current,pageSize), pictureService.getQueryWrapper(pictureQueryDTO));
        //3.1 封装响应结果 为VO对象
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(page,request);
        //4. 缓存至CAFFEINE
        String toCache = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(caffeineKey,toCache);
        //5. 返回数据
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 分页获取图片列表
     * @param pictureQueryDTO
     * @param request
     * @return
     */
    @PostMapping("list/page/vo/multipleCache")
    @ApiOperation("分页获取图片列表多级缓存版")
    public BaseResponse<Page<PictureVO>> listPictureVOWithMultipleCache(@RequestBody PictureQueryDTO pictureQueryDTO,HttpServletRequest request) {
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize>20,ErrorCode.PARAMS_ERROR);
        //只能显示已通过审核的图片
        pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        //1.从caffeine查询数据
        //1.1 caffeine 的key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryDTO);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String caffeineKey = String.format("yuwenpicture:listPictureVOByPage:%s",hashKey);
        //1.2 从caffeine获取数据
        String cacheValue = LOCAL_CACHE.getIfPresent(caffeineKey);
        //2.判断缓存是否命中
        if(cacheValue !=null){
            Page<PictureVO> cachePage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        //TODO 未命中 3.1 从redis查询数据
        String redisKey = String.format("yuwenpicture:listPictureVOByPage:%s",hashKey);
        String redisValue = stringRedisTemplate.opsForValue().get(redisKey);
        //TODO 3.2判断redis 是否命中
        if(redisValue !=null){
            //命中 ，存入caffeine缓存
            LOCAL_CACHE.put(caffeineKey,redisValue);
            Page<PictureVO> cachePage = JSONUtil.toBean(redisValue, Page.class);
            return ResultUtils.success(cachePage);
        }
        //4.未命中，查询数据库
        Page<Picture> page = pictureService.page(new Page<>(current,pageSize), pictureService.getQueryWrapper(pictureQueryDTO));
        //4.1 封装响应结果 为VO对象
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(page,request);
        //5. 缓存数据
        // 5.1至CAFFEINE
        String toCache = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(caffeineKey,toCache);
        //5.2 缓存至redis
        int cacheExpireTime = 300 + RandomUtil.randomInt(0,300);
        stringRedisTemplate.opsForValue().set(redisKey,toCache,cacheExpireTime, TimeUnit.SECONDS);
        //6. 返回数据
        return ResultUtils.success(pictureVOPage);
    }
    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(resultList);
    }
    @PostMapping("/search/color")
    @ApiOperation("根据颜色搜索图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }
    @PostMapping("/flush/color")
    @AuthCheck(mustRole = UserAuthConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> flushPictureColor(Long spaceId, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceId <=0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        boolean result = pictureService.flushPictureColor(spaceId, loginUser);
        return ResultUtils.success(result);
    }
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }


}
